/**
 * OKR 关系树主页面
 * 展示部门、团队、个人的目标层级关系
 */

import React, { useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";
import { Layout, Card, Select, Spin, Alert, Button, Space, Typography } from "antd";
import { ReloadOutlined, PlusOutlined, SettingOutlined, ExpandOutlined, ShrinkOutlined } from "@ant-design/icons";
import type { AppDispatch } from "../../store";
import {
  fetchOKRTree,
  setCurrentQuarter,
  clearError,
  expandAllNodes,
  collapseAllNodes,
  selectOKRNodes,
  selectRootNodes,
  selectOKRLoading,
  selectOKRError,
  selectCurrentQuarter,
  selectQuarters
} from "../../store/okrSlice";
import OKRTreeView from "./components/OKRTreeView";
import OKRNodeDetailModal from "./components/OKRNodeDetailModal";
import CreateOKRModal from "./components/CreateOKRModal";

const { Header, Content } = Layout;
const { Title } = Typography;

/**
 * OKR 关系树页面组件
 */
const OKRTreePage: React.FC = () => {
  const dispatch = useDispatch<AppDispatch>();

  // 从 Redux store 获取状态
  const nodes = useSelector(selectOKRNodes);
  const rootNodes = useSelector(selectRootNodes);
  const loading = useSelector(selectOKRLoading);
  const error = useSelector(selectOKRError);
  const currentQuarter = useSelector(selectCurrentQuarter);
  const quarters = useSelector(selectQuarters);

  // 本地状态
  const [showDetailModal, setShowDetailModal] = React.useState(false);
  const [showCreateModal, setShowCreateModal] = React.useState(false);
  const [selectedNodeId, setSelectedNodeId] = React.useState<string>();

  /**
   * 组件初始化时获取 OKR 数据
   */
  useEffect(() => {
    dispatch(fetchOKRTree(currentQuarter));
  }, [dispatch, currentQuarter]);

  /**
   * 处理季度切换
   * @param quarter 选择的季度
   */
  const handleQuarterChange = (quarter: string) => {
    dispatch(setCurrentQuarter(quarter));
  };

  /**
   * 刷新数据
   */
  const handleRefresh = () => {
    dispatch(fetchOKRTree(currentQuarter));
  };

  /**
   * 清除错误信息
   */
  const handleClearError = () => {
    dispatch(clearError());
  };

  /**
   * 处理节点点击事件
   * @param nodeId 节点ID
   */
  const handleNodeClick = (nodeId: string) => {
    setSelectedNodeId(nodeId);
    setShowDetailModal(true);
  };

  /**
   * 处理创建新节点
   */
  const handleCreateNode = () => {
    setShowCreateModal(true);
  };

  /**
   * 关闭详情弹窗
   */
  const handleCloseDetailModal = () => {
    setShowDetailModal(false);
    setSelectedNodeId(undefined);
  };

  /**
   * 关闭创建弹窗
   */
  const handleCloseCreateModal = () => {
    setShowCreateModal(false);
  };

  /**
   * 创建成功回调
   */
  const handleCreateSuccess = () => {
    setShowCreateModal(false);
    // 刷新数据
    dispatch(fetchOKRTree(currentQuarter));
  };

  /**
   * 展开所有节点
   */
  const handleExpandAll = () => {
    dispatch(expandAllNodes());
  };

  /**
   * 折叠所有节点
   */
  const handleCollapseAll = () => {
    dispatch(collapseAllNodes());
  };

  return (
    <Layout className="min-h-screen bg-gray-50">
      {/* 页面头部 */}
      <Header className="bg-white shadow-sm border-b border-gray-200 px-6">
        <div className="flex items-center justify-between h-full">
          <div className="flex items-center space-x-4">
            <Title level={3} className="!mb-0 text-gray-800">
              OKR 关系树
            </Title>

            {/* 季度选择器 */}
            <Select
              value={currentQuarter}
              onChange={handleQuarterChange}
              className="w-32"
              options={quarters.map(quarter => ({
                label: quarter,
                value: quarter
              }))}
            />
          </div>

          {/* 操作按钮 */}
          <Space>
            <Button icon={<ExpandOutlined />} onClick={handleExpandAll}>
              展开所有
            </Button>
            <Button icon={<ShrinkOutlined />} onClick={handleCollapseAll}>
              折叠所有
            </Button>
            <Button icon={<ReloadOutlined />} onClick={handleRefresh} loading={loading}>
              刷新
            </Button>
            <Button type="primary" icon={<PlusOutlined />} onClick={handleCreateNode}>
              新建目标
            </Button>
            <Button icon={<SettingOutlined />} onClick={() => console.log("设置功能待开发")}>
              设置
            </Button>
          </Space>
        </div>
      </Header>

      {/* 页面内容 */}
      <Content className="p-6">
        <Card className="h-full shadow-sm">
          {/* 错误提示 */}
          {error && (
            <Alert
              message="加载失败"
              description={error}
              type="error"
              showIcon
              closable
              onClose={handleClearError}
              className="mb-4"
            />
          )}

          {/* 加载状态 */}
          {loading && (
            <div className="flex items-center justify-center py-12">
              <Spin size="large" tip="正在加载 OKR 数据..." />
            </div>
          )}

          {/* OKR 树形结构 */}
          {!loading && !error && (
            <div className="h-full">
              {rootNodes.length > 0 ? (
                <OKRTreeView nodes={nodes} rootNodes={rootNodes} onNodeClick={handleNodeClick} />
              ) : (
                <div className="flex flex-col items-center justify-center py-16 text-gray-500">
                  <div className="text-6xl mb-4">🎯</div>
                  <div className="text-xl font-medium mb-2">暂无 OKR 数据</div>
                  <div className="text-sm mb-6">{currentQuarter} 季度还没有设置任何目标</div>
                  <Button type="primary" size="large" icon={<PlusOutlined />} onClick={handleCreateNode}>
                    创建第一个目标
                  </Button>
                </div>
              )}
            </div>
          )}
        </Card>
      </Content>

      {/* 节点详情弹窗 */}
      {selectedNodeId && (
        <OKRNodeDetailModal nodeId={selectedNodeId} visible={showDetailModal} onClose={handleCloseDetailModal} />
      )}

      {/* 创建节点弹窗 */}
      <CreateOKRModal
        visible={showCreateModal}
        quarter={currentQuarter}
        onClose={handleCloseCreateModal}
        onSuccess={handleCreateSuccess}
      />
    </Layout>
  );
};

export default OKRTreePage;
